<template>
  <div class="p-4 page-flex">
    <el-card shadow="never" class="worklog-card">
      <template #header>
        <div class="card-header">
          <h3 class="mb-0">工作日志填写</h3>
          <el-button type="primary" plain @click="goToWorklogRecord">
            <el-icon class="mr-1">
              <View />
            </el-icon>
            查看工作日志记录
          </el-button>
        </div>
      </template>

      <el-form ref="proWorklogFormRef" :model="form" :rules="rules" label-width="120px" class="mt-4">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录日期">
              <el-date-picker clearable v-model="form.logDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择工作日期" style="width: 100%" :disabled="workLogList.length > 0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录人" prop="logRecorder">
              <el-input v-model="currentUserName" placeholder="当前登录用户" readonly disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectManager">
              <el-select
                :model-value="selectedProjectManager ? selectedProjectManager.userName || selectedProjectManager.nickName : ''"
                placeholder="请选择项目负责人" style="width: 100%" clearable :disabled="workLogList.length > 0"
                @click="handleProjectManagerClick" @clear="clearProjectManager">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="handleProjectManagerClick"
                      :disabled="workLogList.length > 0">
                      选择项目负责人
                    </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目选择">
              <el-select v-model="form.proId" placeholder="请先选择项目负责人" clearable filterable remote reserve-keyword
                :remote-method="searchProjects" :loading="projectLoading" style="width: 100%"
                :disabled="!form.proLeadersId" @change="handleProjectChange"
                @visible-change="handleProjectVisibleChange">
                <el-option v-for="project in projectList" :key="project.id"
                  :label="`${project.proName} (${project.proNumber})`" :value="project.id">
                  <template #default>
                    <div class="project-option">
                      <span class="project-name">{{ project.proName }} ({{ project.proNumber }})</span>
                    </div>
                  </template>
                </el-option>
                <template #empty>
                  <div class="text-center p-2">
                    <span v-if="!form.proLeadersId"> 请先选择项目负责人 </span>
                    <span v-else-if="projectSearchKeyword && projectList.length === 0"> 未找到相关项目 </span>
                    <span v-else> 请输入项目名称进行搜索 </span>
                  </div>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 快速选择区域 -->
        <div class="quick-select-section">
          <div class="section-title">
            选择工作内容
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="回款节点" prop="receiveId">
                <el-select v-model="form.receiveId" placeholder="请先选择项目" clearable filterable
                  :loading="receiveLoading" style="width: 100%"
                  :disabled="!form.proId || !form.proLeadersId" @visible-change="handleReceiveVisibleChange"
                  @change="handleReceiveChange">
                  <el-option v-for="receive in receiveList" :key="receive.id" :label="receive.nodeTitle"
                    :value="receive.id">
                    <template #default>
                      <div class="receive-option">
                        <span class="receive-name">{{ receive.nodeTitle }}</span>
                      </div>
                    </template>
                  </el-option>
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="!form.proLeadersId"> 请先选择项目负责人 </span>
                      <span v-else-if="!form.proId"> 请先选择项目 </span>
                      <span v-else> 未找到相关回款节点 </span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="技术流程" prop="planSelect">
                <el-select v-model="form.planSelect" placeholder="请先选择回款节点" clearable filterable
                  :loading="planLoading" style="width: 100%"
                  :disabled="!form.proId || !form.proLeadersId || !form.receiveId"
                  @visible-change="handlePlanVisibleChange" @change="handlePlanSelectionChange">
                  <el-option v-for="plan in planList" :key="plan.id" :label="plan.techFlow" :value="plan.id">
                    <template #default>
                      <div class="plan-option">
                        <span class="plan-name">{{ plan.techFlow }}</span>
                      </div>
                    </template>
                  </el-option>
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="!form.proLeadersId"> 请先选择项目负责人 </span>
                      <span v-else-if="!form.proId"> 请先选择项目 </span>
                      <span v-else-if="!form.receiveId"> 请先选择回款节点 </span>
                      <span v-else> 未找到相关技术流程 </span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作内容" prop="flowSelect">
                <el-select v-model="form.flowSelect" placeholder="请先选择技术流程" clearable filterable
                  :loading="flowLoading" style="width: 100%"
                  :disabled="!form.proId || !form.proLeadersId || !form.receiveId || !form.planSelect"
                  @visible-change="handleFlowVisibleChange" @change="handleFlowSelectionChange">
                  <el-option v-for="flow in flowList" :key="flow.id" :label="flow.workContent" :value="flow.id">
                    <template #default>
                      <div class="flow-option">
                        <span class="flow-name">{{ flow.workContent }}</span>
                      </div>
                    </template>
                  </el-option>
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="!form.proLeadersId"> 请先选择项目负责人 </span>
                      <span v-else-if="!form.proId"> 请先选择项目 </span>
                      <span v-else-if="!form.receiveId"> 请先选择回款节点 </span>
                      <span v-else-if="!form.planSelect"> 请先选择技术流程 </span>
                      <span v-else> 未找到相关工作内容 </span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 快速操作按钮 -->
          <div class="quick-actions">
            <el-button @click="resetForm">
              <el-icon class="mr-1">
                <Refresh />
              </el-icon>
              重置选择
            </el-button>
          </div>
        </div>

        <!-- 工作内容选择框下方的提示信息 -->
        <div v-if="workLogList.length > 0" class="worklog-tip">
          <el-alert title="已有工作日志数据，无法更改项目负责人和记录日期" type="warning" :closable="false" show-icon />
        </div>
      </el-form>

      <!-- 工作日志表格 -->
      <div class="work-table-section mt-6">
        <div class="table-header mb-4">
          <div class="header-left">
            <h4>工作日志明细</h4>
            <el-tag v-if="selectedProjectManagerName" type="primary" size="small" class="project-manager-tag">
              项目负责人: {{ selectedProjectManagerName }}
            </el-tag>
          </div>
        </div>

        <el-table :data="workLogList" border style="width: 100%" v-if="workLogList.length > 0"
          :row-class-name="tableRowClassName">
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column label="项目名称" width="200" align="center" fixed="left">
            <template #default="scope">
              <span class="project-name">{{ scope.row.proName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="回款节点" width="200" align="center" fixed="left" show-overflow-tooltip>
            <template #default="scope">
              <span class="receive-name">{{ scope.row.receiveName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="技术流程" width="200" fixed="left" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span class="tech-flow-display">{{ scope.row.techFlow || scope.row.planName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作内容" prop="flowName" width="300" align="left" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.flowName || '暂无工作内容' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作描述" width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.workDescription" type="textarea"
                placeholder="请输入工作描述（必填）" :rows="3" resize="vertical"
                :class="{ 'is-error': !scope.row.workDescription && scope.row.showValidation }"
                @blur="validateWorkDescription(scope.row)" />
              <span v-else>{{ scope.row.workDescription || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作时长(小时)" width="200" align="center">
            <template #default="scope">
              <NumberInput v-if="scope.row.isEditing" v-model="scope.row.workTime" placeholder="工作时长（必填）" :min="0"
                :precision="2" :required="true" :allow-decimal="true" unit="小时"
                :class="{ 'is-error': (!scope.row.workTime || scope.row.workTime <= 0) && scope.row.showValidation }"
                @blur="validateWorkTime(scope.row)" @change="validateWorkTime(scope.row)" />
              <span v-else>{{ scope.row.workTime ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记录日期" width="200" align="center">
            <template #default="scope">
              <el-date-picker v-if="scope.row.isEditing" v-model="scope.row.logDate" type="date"
                value-format="YYYY-MM-DD" placeholder="选择日期（必填）" style="width: 160px"
                :disabled-date="(time) => time.getTime() > Date.now()"
                :class="{ 'is-error': !scope.row.logDate && scope.row.showValidation }"
                @blur="validateLogDate(scope.row)" />
              <span v-else>{{ parseTime(scope.row.logDate, '{y}-{m}-{d}') || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记录人" width="150" align="center">
            <template #default="scope">
              <span>{{ scope.row.logRecorderName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" type="textarea" placeholder="请输入备注"
                :rows="3" resize="vertical" />
              <span v-else>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>


          <!-- 操作 -->
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <!-- 编辑模式下的操作按钮 -->
              <template v-if="scope.row.isEditing">
                <el-button size="small" @click="cancelEditRow(scope.row)"> 取消 </el-button>
              </template>
              <!-- 查看模式下的操作按钮 -->
              <template v-else>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="editRow(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="removeFromTable(scope.$index)"></el-button>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <el-empty v-else description="暂无工作日志数据，请先选择工作内容并添加到表格" />

        <!-- 底部操作区域 -->
        <div v-if="workLogList.length > 0" class="bottom-actions">
          <!-- 左侧：滑动提示 -->
          <div class="scroll-tip-container">
            <div class="scroll-tip">
              <el-icon class="tip-icon">
                <ArrowLeft />
              </el-icon>
              <span class="tip-text">左右滑动查看更多信息</span>
              <el-icon class="tip-icon">
                <ArrowRight />
              </el-icon>
            </div>
          </div>

          <!-- 右侧：保存/提交按钮 -->
          <div class="save-button-container">
            <el-button type="primary" size="default" v-hasPermi="['project:worklog:add']" @click="openSaveDialog()"
              :disabled="!hasEditingData" :loading="submitLoading">
              暂存工作日志
            </el-button>
            <el-button type="success" size="default" plain @click="submitCurrentWorklogs" :disabled="!hasEditingData">
              提交工作日志
            </el-button>
          </div>
        </div>
      </div>

      <!-- 最近保存记录 -->
      <div class="recent-package-section mt-6">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="最近保存记录" name="recent-packages">
            <template #title>
              <div class="collapse-title">
                <el-icon class="mr-1">
                  <View />
                </el-icon>
                最近保存记录
                <el-tag v-if="recentPackageList.length > 0" type="info" size="small" class="ml-2">
                  {{ recentPackageList.length }}
                </el-tag>
                <RefreshButton @refresh="handleRefreshRecentPackages" :has-permi="['project:worklog:list']"
                  class="ml-2" />
              </div>
            </template>

            <div v-if="recentPackageList.length > 0">
              <el-table :data="recentPackageList" border style="width: 100%" v-loading="recentPackageLoading">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column label="审核标题" prop="auditTitle" min-width="200" show-overflow-tooltip />
                <el-table-column label="审核状态" width="120" align="center">
                  <template #default="scope">
                    <dict-tag :options="approval_commit_status" :value="scope.row.auditStatus || ''" />
                  </template>
                </el-table-column>
                <el-table-column label="项目负责人" prop="proLeaderName" width="120" align="center" show-overflow-tooltip />
                <el-table-column label="保存人" prop="submitter" width="120" align="center" />
                <el-table-column label="保存时间" width="150" align="center">
                  <template #default="scope">
                    {{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                  </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" min-width="200" show-overflow-tooltip />
                <el-table-column label="操作" width="150" align="center" fixed="right">
                  <template #default="scope">
                    <el-tooltip content="修改工作日志" placement="top">
                      <el-button link type="primary" icon="Edit" v-hasPermi="['project:worklog:edit']"
                        @click="handleEditWorklogs(scope.row)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="提交审核" placement="top">
                      <el-button link v-hasPermi="['project:worklog:audit']" type="success" icon="Upload"
                        @click="handleSubmitAudit(scope.row)"
                        :loading="submitAuditLoading === scope.row.id"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <el-empty v-else description="暂无保存记录" />
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 暂存工作日志对话框 -->
      <el-dialog v-model="saveDialogVisible" title="暂存工作日志" width="600px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-form ref="saveFormRef" :model="saveForm" label-width="70px">
          <el-form-item label="保存时间">
            <el-input v-model="saveForm.saveTime" readonly disabled />
          </el-form-item>
          <el-form-item label="保存人">
            <el-input v-model="saveForm.saveUser" readonly disabled />
          </el-form-item>
          <el-form-item label="审核标题" prop="auditTitle">
            <el-input v-model="saveForm.auditTitle" type="textarea" placeholder="请输入审核标题" :rows="3" resize="vertical" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="saveForm.remark" type="textarea" placeholder="请输入备注信息" :rows="3" resize="vertical" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelSave">取消</el-button>
            <el-button type="primary" @click="confirmSave" :loading="submitLoading"> 确认暂存 </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 编辑工作日志对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑工作日志" width="1200px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="edit-dialog-content">
          <!-- 审核信息 -->
          <div class="audit-info mb-4">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="审核标题">{{ currentAuditInfo.auditTitle || '-' }}</el-descriptions-item>
              <el-descriptions-item label="审核状态">
                <dict-tag :options="approval_commit_status" :value="currentAuditInfo.auditStatus || ''" />
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人">{{ currentAuditInfo.proLeaderName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="保存人">{{ currentAuditInfo.submitter || '-' }}</el-descriptions-item>
              <el-descriptions-item label="保存时间">
                {{ parseTime(currentAuditInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">{{ currentAuditInfo.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 工作日志编辑表格 -->
          <div class="edit-table-section">
            <div class="table-header mb-4">
              <h4>工作日志明细</h4>
            </div>

            <el-table :data="editWorklogList" border style="width: 100%" v-loading="editLoading">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="项目名称" width="200" align="center">
                <template #default="scope">
                  <span class="project-name">{{ scope.row.proName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="回款节点" width="200" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span class="receive-name">{{ scope.row.receiveName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="技术流程" width="200" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span class="tech-flow-display">{{ scope.row.techFlow || scope.row.planName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="工作内容" prop="workContent" width="300" align="left" show-overflow-tooltip>
                <template #default="scope">
                  <span>{{ scope.row.workContent || '暂无工作内容' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="工作描述" width="300">
                <template #default="scope">
                  <el-input v-model="scope.row.workDescription" type="textarea" placeholder="请输入工作描述（必填）" :rows="3"
                    resize="vertical" @input="markAsChanged(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="工作时长(小时)" width="200" align="center">
                <template #default="scope">
                  <NumberInput v-model="scope.row.workTime" placeholder="工作时长（必填）" :min="0" :precision="2"
                    :required="true" :allow-decimal="true" unit="小时" @change="markAsChanged(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="记录日期" width="200" align="center">
                <template #default="scope">
                  <el-date-picker v-model="scope.row.logDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="选择日期（必填）" style="width: 160px" :disabled-date="(time) => time.getTime() > Date.now()"
                    @change="markAsChanged(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="记录人" width="150" align="center">
                <template #default="scope">
                  <span>{{ scope.row.logRecorderName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="300">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" type="textarea" placeholder="请输入备注" :rows="3" resize="vertical"
                    @input="markAsChanged(scope.row)" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="saveEditChanges" v-hasPermi="['project:worklog:edit']"
              :loading="editSubmitLoading">
              确认修改
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 审核流程配置对话框 -->
      <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'WORK-LOG-AUDIT'"
        :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置工作日志审核流程" @confirm="handleApprovalConfirm"
        @cancel="handleApprovalCancel" />

      <!-- 项目负责人选择器 -->
      <UserSelector v-model:visible="showProjectManagerSelector" title="选择项目负责人" :selected-user-ids="form.proLeadersId"
        :selected-user-names="selectedProjectManagerName" :multiple="false"
        @confirmWithIds="handleProjectManagerConfirm" @cancel="handleProjectManagerCancel" />
    </el-card>
  </div>
</template>

<script setup name="ProWorklog" lang="ts">
import RefreshButton from '@/views/project/components/RefreshButton.vue';
import { batchAddProWorklog, recentAuditList, getWorklogsByAuditId, batchEditProWorklog } from '@/api/project/log/worklog';
import { pageListForQuery } from '@/api/project/init/proInfo';
import { listProFlow } from '@/api/project/plan/flow';
import { listProPlan } from '@/api/project/plan';
import { getReceiveMoneyNodesByProId } from '@/api/project/receive';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import type { ProFlowVO } from '@/api/project/plan/flow/types';
import type { ProPlanVO } from '@/api/project/plan/types';
import type { ProReceiveMoneyVO } from '@/api/project/receive/types';
import { useUserStore } from '@/store/modules/user';
import { NumberInput } from '@/components/NumberInput';
import { parseTime } from '@/utils/ruoyi';
import ApprovalFlow from '@/components/ApprovalFlow/index.vue';
import UserSelector from '@/components/UserSelector/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const router = useRouter();

// 字典数据
const { approval_commit_status } = toRefs<any>(proxy?.useDict('approval_commit_status'));

const projectLoading = ref(false);
const flowLoading = ref(false);
const planLoading = ref(false);
const receiveLoading = ref(false);
const submitLoading = ref(false);

const recentPackageLoading = ref(false);
const submitAuditLoading = ref<string | number>('');
const proWorklogFormRef = ref<ElFormInstance>();
const auditIdForApproval = ref<string | number | undefined>(undefined);

// 保存对话框相关
const saveDialogVisible = ref(false);
const saveFormRef = ref<ElFormInstance>();
const saveForm = reactive({
  saveTime: '',
  saveUser: '',
  auditTitle: '',
  remark: ''
});

// 编辑对话框相关
const editDialogVisible = ref(false);
const editLoading = ref(false);
const editSubmitLoading = ref(false);
const editWorklogList = ref<any[]>([]);
const currentAuditInfo = ref<any>({});
const originalEditData = ref<any[]>([]);

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);

// 最近保存记录相关
const activeCollapse = ref(['recent-packages']);
const recentPackageList = ref<any[]>([]);

// 用户信息
const currentUserName = ref('');
const currentUserId = ref('');

const projectList = ref<ProInfoVO[]>([]);
const flowList = ref<ProFlowVO[]>([]);
const planList = ref<ProPlanVO[]>([]);
const receiveList = ref<ProReceiveMoneyVO[]>([]);
const workLogList = ref<WorkLogItem[]>([]);

// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const planSearchKeyword = ref('');
const receiveSearchKeyword = ref('');

// 项目负责人选择器相关
const showProjectManagerSelector = ref(false);
const selectedProjectManager = ref<any>(null);
const selectedProjectManagerName = ref<string>('');

// 计算是否有编辑状态的数据
const hasEditingData = computed(() => {
  return workLogList.value.some((item) => item.isEditing);
});

// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
let flowSearchTimer: NodeJS.Timeout | null = null;
let planSearchTimer: NodeJS.Timeout | null = null;
let receiveSearchTimer: NodeJS.Timeout | null = null;

/** 清空搜索关键词 */
const clearSearchKeywords = () => {
  projectSearchKeyword.value = '';
  flowSearchKeyword.value = '';
  planSearchKeyword.value = '';
  receiveSearchKeyword.value = '';
};

/** 清理搜索计时器 */
const clearSearchTimers = () => {
  if (projectSearchTimer) {
    clearTimeout(projectSearchTimer);
    projectSearchTimer = null;
  }
  if (flowSearchTimer) {
    clearTimeout(flowSearchTimer);
    flowSearchTimer = null;
  }
  if (planSearchTimer) {
    clearTimeout(planSearchTimer);
    planSearchTimer = null;
  }
  if (receiveSearchTimer) {
    clearTimeout(receiveSearchTimer);
    receiveSearchTimer = null;
  }
};

/** 清空选择列表 */
const clearSelectionLists = () => {
  projectList.value = [];
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
};

/** 清空表单选择 */
const clearFormSelections = () => {
  form.value.proId = undefined;
  form.value.receiveId = undefined;
  form.value.planSelect = undefined;
  form.value.flowSelect = undefined;
};

// 工作日志表格项接口
interface WorkLogItem {
  id?: string;
  proId?: number | string;
  proName?: string;
  receiveId?: number | string;
  receiveName?: string;
  planId?: number | string;
  planName?: string;
  planContent?: string;
  techFlow?: string; // 技术流程名称
  flowId?: number | string;
  flowName?: string;
  logDate?: string;
  logRecorder?: string;
  logRecorderName?: string;
  workDescription?: string;
  workTime?: number;
  remark?: string;
  showValidation?: boolean; // 控制是否显示验证错误信息
  isEditing?: boolean; // 是否处于编辑状态
  originalData?: Partial<WorkLogItem> | null; // 取消时恢复
}

const initFormData = {
  id: undefined,
  proId: undefined,
  planSelect: undefined as unknown as string | number | undefined,
  flowSelect: undefined as unknown as string | number | undefined, // 工作内容选择
  logDate: undefined,
  logRecorder: undefined,
  proLeadersId: undefined as unknown as string | undefined, // 项目负责人ID
  receiveId: undefined as unknown as string | number | undefined // 回款节点ID
};

const data = reactive({
  form: { ...initFormData },
  rules: {
    proLeadersId: [{ required: true, message: '请选择项目负责人', trigger: 'change' }]
  }
});

const { form, rules } = toRefs(data);

/** 初始化用户信息 */
const initUserInfo = () => {
  currentUserName.value = userStore.name || '';
  currentUserId.value = userStore.userId?.toString() || '';

  // 设置默认日期为今天
  if (!form.value.logDate) {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    form.value.logDate = `${year}-${month}-${day}`;
  }
};

/** 远程搜索项目 */
const searchProjects = (query: string) => {
  // 如果没有选择项目负责人，不执行搜索
  if (!form.value.proLeadersId) {
    return;
  }

  projectSearchKeyword.value = query;

  if (projectSearchTimer) {
    clearTimeout(projectSearchTimer);
  }

  projectSearchTimer = setTimeout(() => {
    // 如果查询为空，加载所有项目；否则按名称搜索
    getProjectList(query || '');
  }, 300); // 300ms防抖
};

// 已移除 remote 搜索：回款节点

// 已移除 remote 搜索：技术流程

// 已移除 remote 搜索：工作内容

/** 获取项目列表 */
const getProjectList = async (searchKeyword = '') => {
  try {
    projectLoading.value = true;
    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50, // 减少单次加载数量
      auditStatus: '3', // 固定携带auditStatus=3参数
      proName: searchKeyword || undefined, // 支持名称搜索
      proLeadersId: form.value.proLeadersId || undefined // 携带项目负责人ID
    });
    projectList.value = res.rows || [];
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

/** 获取回款节点列表 */
const getReceiveList = async (searchKeyword = '') => {
  try {
    receiveLoading.value = true;
    const res = await getReceiveMoneyNodesByProId(form.value.proId!);
    let receives = res.data || [];

    // 如果有关键词，进行过滤
    if (searchKeyword) {
      receives = receives.filter((receive: ProReceiveMoneyVO) =>
        receive.nodeTitle && receive.nodeTitle.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }

    receiveList.value = receives;
  } catch (error) {
    console.error('获取回款节点列表失败:', error);
    ElMessage.error('获取回款节点列表失败');
  } finally {
    receiveLoading.value = false;
  }
};

/** 获取计划列表 */
const getPlanList = async (receiveId: number | string, searchKeyword = '') => {
  if (!receiveId) {
    planList.value = [];
    return;
  }

  try {
    planLoading.value = true;
    const res = await listProPlan({
      receiveId: receiveId
    });
    let plans = res.data || [];

    // 如果有关键词，进行过滤
    if (searchKeyword) {
      plans = plans.filter((plan: ProPlanVO) =>
        plan.techFlow && plan.techFlow.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }

    planList.value = plans;
  } catch (error) {
    console.error('获取计划列表失败:', error);
    ElMessage.error('获取计划列表失败');
    planList.value = [];
  } finally {
    planLoading.value = false;
  }
};

/** 获取工作内容列表 */
const getFlowList = async (planId: number | string, searchKeyword = '') => {
  if (!planId) {
    flowList.value = [];
    return;
  }

  try {
    flowLoading.value = true;
    const res = await listProFlow({
      planId: planId
    } as any);
    let flows = res.data || [];

    // 如果有关键词，进行过滤
    if (searchKeyword) {
      flows = flows.filter((flow: ProFlowVO) =>
        flow.workContent && flow.workContent.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }

    flowList.value = flows;
  } catch (error) {
    console.error('获取工作内容列表失败:', error);
    ElMessage.error('获取工作内容列表失败');
    flowList.value = [];
  } finally {
    flowLoading.value = false;
  }
};

/** 处理项目下拉框显示状态变化 */
const handleProjectVisibleChange = (visible: boolean) => {
  if (visible && form.value.proLeadersId) {
    // 下拉框打开时，如果有项目负责人但没有数据则加载默认数据
    if (projectList.value.length === 0) {
      // 触发远程搜索方法，传入空字符串来加载所有项目
      searchProjects('');
    }
  }
};



/** 处理回款下拉框显示状态变化 */
const handleReceiveVisibleChange = (visible: boolean) => {
  if (visible && form.value.proLeadersId && form.value.proId) {
    // 下拉框打开时，如果有项目负责人和项目但没有数据则加载默认数据
    if (receiveList.value.length === 0) {
      // 直接加载全部回款节点
      getReceiveList('');
    }
  }
};

/** 处理计划下拉框显示状态变化 */
const handlePlanVisibleChange = (visible: boolean) => {
  if (visible && form.value.proLeadersId && form.value.proId && form.value.receiveId && planList.value.length === 0) {
    // 下拉框打开时，如果有项目负责人、项目和回款节点但没有计划数据则加载
    getPlanList(form.value.receiveId!, '');
  }
};

/** 处理工作内容下拉框显示状态变化 */
const handleFlowVisibleChange = (visible: boolean) => {
  if (visible && form.value.proLeadersId && form.value.proId && form.value.receiveId && form.value.planSelect && flowList.value.length === 0) {
    // 下拉框打开时，如果有项目负责人、项目、回款节点和技术流程但没有工作内容数据则加载
    getFlowList(form.value.planSelect!, '');
  }
};

/** 处理项目选择变化 */
const handleProjectChange = (value: number | string | undefined) => {
  // 清空后续选择，但不清空项目ID
  form.value.receiveId = undefined;
  form.value.planSelect = undefined;
  form.value.flowSelect = undefined;

  // 清空后续选择列表
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];

  // 清空搜索关键词
  clearSearchKeywords();

  // 项目改变时不清空工作日志列表，允许多个项目的数据共存

  if (value && form.value.proLeadersId) {
    // 直接加载回款列表
    getReceiveList('');
  }
};

/** 处理回款选择变化 */
const handleReceiveChange = (value: number | string | undefined) => {
  form.value.planSelect = undefined; // 清空计划选择
  form.value.flowSelect = undefined; // 清空工作内容选择
  planList.value = []; // 清空计划列表
  flowList.value = []; // 清空工作内容列表
  clearSearchKeywords(); // 清空搜索关键词

  // 回款改变时不清空工作日志列表，允许多个回款的数据共存

  if (value && form.value.proLeadersId && form.value.proId) {
    // 直接加载计划列表
    getPlanList(form.value.receiveId!, '');
  }
};

/** 处理计划选择变化 */
const handlePlanSelectionChange = (selectedPlanId: number | string | undefined) => {
  if (!selectedPlanId) return;

  // 清空工作内容选择
  form.value.flowSelect = undefined;
  flowList.value = [];
  clearSearchKeywords(); // 清空搜索关键词

  // 获取所选计划
  const plan = planList.value.find((p) => p.id === selectedPlanId);
  if (!plan) return;

  // 加载该计划对应的工作内容列表
  getFlowList(selectedPlanId, '');

  // 获取当前选中的项目信息
  const selectedProject = projectList.value.find((project) => project.id === form.value.proId);

  // 获取当前选中的回款节点信息
  const selectedReceive = receiveList.value.find((receive) => receive.id === form.value.receiveId);

  // 不自动添加到表格，而是让用户手动选择工作内容
  // 不清空选择，保持当前选中的技术流程
  // form.value.planSelect = undefined;

  // ElMessage.success('技术流程已选择，请选择工作内容');
};

/** 处理工作内容选择变化 */
const handleFlowSelectionChange = (selectedFlowId: number | string | undefined) => {
  if (!selectedFlowId) return;

  // 获取所选工作内容
  const flow = flowList.value.find((f) => f.id === selectedFlowId);
  if (!flow) return;

  // 获取当前选中的项目信息
  const selectedProject = projectList.value.find((project) => project.id === form.value.proId);

  // 获取当前选中的回款节点信息
  const selectedReceive = receiveList.value.find((receive) => receive.id === form.value.receiveId);

  // 获取当前选中的技术流程信息
  const selectedPlan = planList.value.find((plan) => plan.id === form.value.planSelect);

  workLogList.value.push({
    // 未保存数据不设置后端 id，用于区分状态
    proId: form.value.proId,
    proName: selectedProject ? `${selectedProject.proName} (${selectedProject.proNumber})` : '',
    receiveId: form.value.receiveId,
    receiveName: selectedReceive ? selectedReceive.nodeTitle : '',
    planId: selectedPlan?.id,
    planName: selectedPlan?.techFlow || '',
    planContent: selectedPlan?.remark || '',
    techFlow: selectedPlan?.techFlow || '', // 添加技术流程名称
    flowId: flow.id,
    flowName: flow.workContent || '',
    logDate: form.value.logDate,
    logRecorder: currentUserId.value,
    logRecorderName: currentUserName.value,
    workDescription: '',
    workTime: undefined,
    remark: '',
    showValidation: false, // 初始时不显示验证错误
    isEditing: true,
    originalData: null
  });

  // 清空选择，允许再次选择同一工作内容
  form.value.flowSelect = undefined;

  ElMessage.success('已添加一条工作内容到表格');
};



/** 从表格中移除 */
const removeFromTable = (index: number) => {
  const removedItem = workLogList.value[index];
  workLogList.value.splice(index, 1);

  ElMessage.success('移除成功');
};

/** 开始编辑（仅已保存的数据允许切换编辑） */
const editRow = (row: WorkLogItem) => {
  row.originalData = JSON.parse(JSON.stringify(row));
  row.isEditing = true;
};

/** 取消编辑，恢复原值（未保存的新增行则移除） */
const cancelEditRow = (row: WorkLogItem) => {
  if (!row.id) {
    const idx = workLogList.value.indexOf(row);
    if (idx > -1) workLogList.value.splice(idx, 1);
    return;
  }
  if (row.originalData) {
    Object.assign(row, row.originalData);
    row.isEditing = false;
    row.originalData = null;
  } else {
    row.isEditing = false;
  }
};

/** 验证工作描述 */
const validateWorkDescription = (item: WorkLogItem) => {
  item.showValidation = true;
  if (!item.workDescription || item.workDescription.trim() === '') {
    return false;
  }
  return true;
};

/** 验证工作时长 */
const validateWorkTime = (item: WorkLogItem) => {
  item.showValidation = true;
  const workTime = Number(item.workTime);
  if (!item.workTime || workTime <= 0 || isNaN(workTime)) {
    return false;
  }
  return true;
};

/** 验证记录日期 */
const validateLogDate = (item: WorkLogItem) => {
  item.showValidation = true;
  if (!item.logDate) {
    return false;
  }
  return true;
};

/** 打开保存对话框（仅保存，不提交审核） */
const openSaveDialog = async () => {
  if (!hasEditingData.value) {
    ElMessage.warning('没有处于编辑状态的数据可以保存');
    return;
  }

  // 验证编辑状态的数据
  const editingItems = workLogList.value.filter((item) => item.isEditing);
  const validationErrors: string[] = [];
  editingItems.forEach((item, index) => {
    const dateValid = validateLogDate(item);
    const descValid = validateWorkDescription(item);
    const timeValid = validateWorkTime(item);
    if (!dateValid || !descValid || !timeValid) {
      validationErrors.push(`第${index + 1}行：有必填属性未填写`);
    }
  });

  if (validationErrors.length > 0) {
    ElMessage.error(`保存失败：\n${validationErrors.join('\n')}`);
    return;
  }

  // 初始化保存表单数据
  saveForm.saveTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
  saveForm.saveUser = currentUserName.value;
  saveForm.auditTitle = `工作日志保存 - ${parseTime(new Date(), '{y}-{m}-{d}')}`;
  saveForm.remark = `保存了 ${editingItems.length} 条工作日志`;

  // 显示保存对话框
  saveDialogVisible.value = true;
};

/** 取消保存 */
const cancelSave = () => {
  saveDialogVisible.value = false;
  // 重置表单
  saveForm.auditTitle = '';
  saveForm.remark = '';
};

/** 确认保存 */
const confirmSave = async () => {
  try {
    submitLoading.value = true;

    // 获取编辑状态的数据
    const editingItems = workLogList.value.filter((item) => item.isEditing);

    if (editingItems.length === 0) {
      ElMessage.warning('没有处于编辑状态的数据可以保存');
      return;
    }

    // 构建批量提交数据
    const submitData = {
      auditTitle: saveForm.auditTitle || `工作日志保存 - ${parseTime(new Date(), '{y}-{m}-{d}')}`,
      remark: saveForm.remark || `保存了 ${editingItems.length} 条工作日志`,
      proLeaderId: form.value.proLeadersId, // 项目负责人ID添加到审核信息中
      worklogs: editingItems.map((item) => ({
        proId: item.proId,
        planId: item.planId,
        flowId: item.flowId,
        receiveId: item.receiveId,
        receiveName: item.receiveName,
        logDate: item.logDate,
        logRecorder: Number(item.logRecorder),
        workDescription: item.workDescription?.trim(),
        workTime: Number(item.workTime),
        remark: item.remark?.trim()
      }))
    };

    // 调用批量保存API
    await batchAddProWorklog(submitData);
    ElMessage.success(`成功保存 ${editingItems.length} 条工作日志`);

    // 关闭对话框
    saveDialogVisible.value = false;

    // 清空工作日志列表并刷新
    workLogList.value = [];
    resetForm();
    await loadRecentPackageList();

    // 不自动提交审核，提交功能由"最近保存记录"区域触发
  } catch (error: any) {
    console.error('批量保存失败:', error);
    const errorMessage = error?.response?.data?.msg || error?.message || '保存失败，请重试';
    ElMessage.error(errorMessage);
  } finally {
    submitLoading.value = false;
  }
};

/** 跳转到工作日志记录页面 */
const goToWorklogRecord = () => {
  // 使用相对路径跳转，避免刷新页面
  router.push('./worklog/record');
};

/** 刷新最近保存记录 */
const handleRefreshRecentPackages = async () => {
  try {
    await loadRecentPackageList();
    ElMessage.success('刷新最近保存记录成功');
  } catch (error) {
    console.error('刷新最近保存记录失败:', error);
    ElMessage.error('刷新最近保存记录失败');
  }
};

/** 加载最近保存记录 */
const loadRecentPackageList = async () => {
  try {
    recentPackageLoading.value = true;
    const res = await recentAuditList();
    recentPackageList.value = res.data || [];
  } catch (error) {
    console.error('加载最近保存记录失败:', error);
    ElMessage.error('加载最近保存记录失败');
  } finally {
    recentPackageLoading.value = false;
  }
};

/** 修改工作日志 */
const handleEditWorklogs = async (row: any) => {
  try {
    editLoading.value = true;

    // 设置当前审核信息
    currentAuditInfo.value = row;

    // 获取该审核下的工作日志列表
    const res = await getWorklogsByAuditId(row.id);
    const worklogs = res.data || [];

    // 设置编辑列表和原始数据
    editWorklogList.value = worklogs.map((item: any) => ({
      ...item,
      isChanged: false
    }));
    originalEditData.value = JSON.parse(JSON.stringify(worklogs));

    // 显示编辑对话框
    editDialogVisible.value = true;
  } catch (error) {
    console.error('修改工作日志失败:', error);
    ElMessage.error('修改工作日志失败');
  } finally {
    editLoading.value = false;
  }
};

/** 标记数据已更改 */
const markAsChanged = (row: any) => {
  row.isChanged = true;
};

/** 取消编辑 */
const cancelEdit = () => {
  editDialogVisible.value = false;
  editWorklogList.value = [];
  originalEditData.value = [];
  currentAuditInfo.value = {};
};

/** 保存编辑修改 */
const saveEditChanges = async () => {
  try {
    editSubmitLoading.value = true;

    // 验证必填字段
    const validationErrors: string[] = [];
    editWorklogList.value.forEach((item, index) => {
      if (!item.workDescription || item.workDescription.trim() === '' ||
        !item.workTime || Number(item.workTime) <= 0 ||
        !item.logDate) {
        validationErrors.push(`第${index + 1}行：有必填属性未填写`);
      }
    });

    if (validationErrors.length > 0) {
      ElMessage.error(`保存失败：\n${validationErrors.join('\n')}`);
      return;
    }

    // 构建批量修改数据
    const batchUpdateData = editWorklogList.value.map((item) => ({
      id: item.id,
      proId: item.proId,
      receiveId: item.receiveId,
      planId: item.planId,
      flowId: item.flowId,
      receiveName: item.receiveName,
      logDate: item.logDate,
      logRecorder: Number(item.logRecorder),
      workDescription: item.workDescription?.trim(),
      workTime: Number(item.workTime),
      remark: item.remark?.trim()
    }));

    // 调用批量修改接口
    await batchEditProWorklog(batchUpdateData);

    ElMessage.success('工作日志修改成功');
    editDialogVisible.value = false;

    // 刷新最近保存记录
    await loadRecentPackageList();
  } catch (error: any) {
    console.error('保存修改失败:', error);
    const errorMessage = error?.response?.data?.msg || error?.message || '保存修改失败，请重试';
    ElMessage.error(errorMessage);
  } finally {
    editSubmitLoading.value = false;
  }
};

/** 提交审核 */
const handleSubmitAudit = async (row: any) => {
  try {
    // 设置当前要提交审核的行数据
    currentSubmitAuditRow.value = row;
    // 绑定业务ID并显示审核流程配置对话框
    auditIdForApproval.value = row?.id;
    approvalFlowVisible.value = true;
  } catch (error) {
    console.error('提交审核失败:', error);
    ElMessage.error('提交审核失败');
  }
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
    // 刷新最近保存记录
    await loadRecentPackageList();
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
};

/** 重置快速选择工作内容 */
const resetForm = () => {
  // 只重置快速选择工作内容区域的数据
  form.value.receiveId = undefined;
  form.value.planSelect = undefined;
  form.value.flowSelect = undefined;
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
  receiveSearchKeyword.value = '';
  planSearchKeyword.value = '';
  flowSearchKeyword.value = '';

  // 清理相关计时器
  clearSearchTimers();

  // ElMessage.success('日志表单已重置');
};

/** 处理项目负责人选择确认 */
const handleProjectManagerConfirm = (data: { users: any[]; userIds: string; userNames: string; }) => {
  if (workLogList.value.length > 0) {
    ElMessage.warning('已有工作日志数据，请先删除所有工作日志后再切换项目负责人');
    showProjectManagerSelector.value = false;
    return;
  }

  if (data.users && data.users.length > 0) {
    selectedProjectManager.value = data.users[0];
    selectedProjectManagerName.value = data.userNames || '';
    form.value.proLeadersId = data.userIds || '';

    // 项目负责人改变时，清空项目选择和项目列表
    form.value.proId = undefined;
    form.value.receiveId = undefined;
    form.value.planSelect = undefined;
    form.value.flowSelect = undefined;
    projectList.value = [];
    receiveList.value = [];
    planList.value = [];
    flowList.value = [];
    projectSearchKeyword.value = '';
    receiveSearchKeyword.value = '';
    planSearchKeyword.value = '';
    flowSearchKeyword.value = '';
  } else {
    selectedProjectManager.value = null;
    selectedProjectManagerName.value = '';
    form.value.proLeadersId = '';

    // 清空项目负责人时，也清空项目选择和项目列表
    form.value.proId = undefined;
    form.value.receiveId = undefined;
    form.value.planSelect = undefined;
    form.value.flowSelect = undefined;
    projectList.value = [];
    receiveList.value = [];
    planList.value = [];
    flowList.value = [];
    projectSearchKeyword.value = '';
    receiveSearchKeyword.value = '';
    planSearchKeyword.value = '';
    flowSearchKeyword.value = '';
  }
  showProjectManagerSelector.value = false;
};

/** 处理项目负责人取消 */
const handleProjectManagerCancel = () => {
  showProjectManagerSelector.value = false;
};

/** 处理项目负责人点击事件 */
const handleProjectManagerClick = () => {
  if (workLogList.value.length > 0) {
    ElMessage.warning('已有工作日志数据，请先删除所有工作日志后再切换项目负责人');
    return;
  }
  showProjectManagerSelector.value = true;
};

/** 清空项目负责人 */
const clearProjectManager = () => {
  if (workLogList.value.length > 0) {
    ElMessage.warning('已有工作日志数据，请先删除所有工作日志后再切换项目负责人');
    return;
  }

  selectedProjectManager.value = null;
  selectedProjectManagerName.value = '';
  form.value.proLeadersId = '';

  // 清空项目负责人时，也清空项目选择和项目列表
  form.value.proId = undefined;
  form.value.receiveId = undefined;
  form.value.planSelect = undefined;
  form.value.flowSelect = undefined;
  projectList.value = [];
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
  projectSearchKeyword.value = '';
  receiveSearchKeyword.value = '';
  planSearchKeyword.value = '';
  flowSearchKeyword.value = '';
};

// 监听记录日期变化，清空项目和流程选择，但保留列表数据
watch(
  () => form.value.logDate,
  (newDate, oldDate) => {
    // 只有当日期真正发生变化时才清空，避免初始化时触发
    if (oldDate && newDate !== oldDate) {
      // 如果有工作日志数据，不允许更改日期
      if (workLogList.value.length > 0) {
        ElMessage.warning('已有工作日志数据，请先删除所有工作日志后再更改记录日期');
        // 恢复原来的日期
        form.value.logDate = oldDate;
        return;
      }

      // 清空项目选择
      form.value.proId = undefined;
      form.value.receiveId = undefined;
      form.value.planSelect = undefined;
      form.value.flowSelect = undefined;
      // 清空项目负责人
      selectedProjectManager.value = null;
      selectedProjectManagerName.value = '';
      form.value.proLeadersId = '';

      // 清空项目和计划列表
      projectList.value = [];
      receiveList.value = [];
      planList.value = [];
      flowList.value = [];

      // 清空搜索关键词
      clearSearchKeywords();

      // 不清空workLogList，保留已有的列表数据
      ElMessage.info('记录日期已更改，请重新选择项目负责人、项目、回款节点、技术流程和工作内容');
    }
  }
);

// 页面挂载时初始化用户信息
onMounted(() => {
  initUserInfo();
  loadRecentPackageList();
});

// 行样式：编辑中的行高亮显示
const tableRowClassName = ({ row }: { row: WorkLogItem }) => (row.isEditing ? 'editing-row' : '');

/** 提交工作日志（保存+审核） */
const submitCurrentWorklogs = async () => {
  if (!hasEditingData.value) {
    ElMessage.warning('没有处于编辑状态的数据可以提交');
    return;
  }

  // 验证编辑状态的数据
  const editingItems = workLogList.value.filter((item) => item.isEditing);
  const validationErrors: string[] = [];
  editingItems.forEach((item, index) => {
    const dateValid = validateLogDate(item);
    const descValid = validateWorkDescription(item);
    const timeValid = validateWorkTime(item);
    if (!dateValid || !descValid || !timeValid) {
      validationErrors.push(`第${index + 1}行：有必填属性未填写`);
    }
  });

  if (validationErrors.length > 0) {
    ElMessage.error(`提交失败：\n${validationErrors.join('\n')}`);
    return;
  }

  try {
    submitLoading.value = true;

    // 构建批量提交数据（和暂存功能一样的数据结构）
    const submitData = {
      auditTitle: `工作日志提交 - ${parseTime(new Date(), '{y}-{m}-{d}')}`,
      remark: `提交了 ${editingItems.length} 条工作日志`,
      proLeaderId: form.value.proLeadersId,
      worklogs: editingItems.map((item) => ({
        proId: item.proId,
        planId: item.planId,
        flowId: item.flowId,
        receiveId: item.receiveId,
        receiveName: item.receiveName,
        logDate: item.logDate,
        logRecorder: Number(item.logRecorder),
        workDescription: item.workDescription?.trim(),
        workTime: Number(item.workTime),
        remark: item.remark?.trim()
      }))
    };

    // 1. 先调用批量保存API
    const saveResponse = await batchAddProWorklog(submitData);
    console.log('工作日志保存成功，返回的审核记录ID:', saveResponse.data);

    // 2. 获取返回的审核记录ID，用于触发审核流程
    const auditRecordId = saveResponse.data;
    if (auditRecordId) {
      // 设置审核相关参数
      auditIdForApproval.value = auditRecordId;

      // 3. 触发审核流程配置对话框
      approvalFlowVisible.value = true;

      ElMessage.success(`成功保存 ${editingItems.length} 条工作日志，正在配置审核流程...`);

      // 清空工作日志列表
      workLogList.value = [];
      resetForm();
    } else {
      ElMessage.error('保存成功但无法获取审核记录ID，请手动提交审核');
    }

  } catch (error: any) {
    console.error('提交工作日志失败:', error);
    const errorMessage = error?.response?.data?.msg || error?.message || '提交失败，请重试';
    ElMessage.error(errorMessage);
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.worklog-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.worklog-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  overflow-y: auto;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.text-center {
  text-align: center;
}

.mr-1 {
  margin-right: 4px;
}

.mt-4 {
  margin-top: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-card__body) {
  padding: 20px 30px;
}

:deep(.el-select-dropdown__empty) {
  padding: 16px 0;
  color: #909399;
  font-size: 14px;
}

/* 搜索框提示样式 */
:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

/* 选项样式优化 */
:deep(.el-select-dropdown__item) {
  padding: 10px 20px;
  min-height: 40px;
  line-height: 1.4;
  white-space: nowrap;
  height: auto;
}

:deep(.el-select-dropdown__item.is-hovering) {
  background-color: var(--el-color-primary-light-9);
}

/* 选项样式 */
:deep(.project-option),
:deep(.receive-option),
:deep(.plan-option),
:deep(.flow-option) {
  display: flex;
  align-items: center;
  padding: 4px 0;
  width: 100%;
  line-height: 1.4;
}

:deep(.project-option .project-name) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.plan-name) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.flow-name) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 项目名称样式 */
.project-name {
  font-weight: 600;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

/* 回款节点名称样式 */
.receive-name {
  font-weight: 600;
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

/* 表格区域样式 */
.work-table-section {
  margin-top: 24px;
  border-top: 1px solid #e4e7ed;
  padding-top: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.project-manager-tag {
  margin-left: 8px;
}

.table-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

/* 表格内textarea样式优化 */
:deep(.el-table .el-textarea__inner) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

:deep(.el-table .el-textarea__inner:focus) {
  border-color: var(--el-color-primary);
}

/* 表单验证错误样式 */
:deep(.is-error .el-input__wrapper),
:deep(.is-error .el-textarea__inner),
:deep(.is-error .el-input-number .el-input__wrapper),
:deep(.is-error .number-input-wrapper .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

:deep(.is-error .el-input__wrapper:hover),
:deep(.is-error .el-textarea__inner:hover),
:deep(.is-error .el-input-number .el-input__wrapper:hover),
:deep(.is-error .number-input-wrapper .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

/* 编辑状态行背景色（参照流程拆分页） */
:deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 工具类 */
.mt-6 {
  margin-top: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 最近保存记录区域样式 */
.recent-package-section {
  margin-top: 24px;
  border-top: 1px solid #e4e7ed;
  padding-top: 24px;
}

.collapse-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.ml-2 {
  margin-left: 8px;
}

/* 折叠面板样式优化 */
:deep(.el-collapse-item__header) {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 12px 16px;
  font-weight: 600;
}

:deep(.el-collapse-item__content) {
  padding: 16px 0;
}

:deep(.el-collapse-item__wrap) {
  border: none;
}

/* 底部操作区域样式 */
.bottom-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 12px 0;
  border-top: 1px solid #e4e7ed;
}

/* 滑动提示样式 */
.scroll-tip-container {
  display: flex;
  align-items: center;
}

.scroll-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  padding: 6px 12px;
  border-radius: 4px;
  display: inline-flex;
}

.tip-icon {
  font-size: 14px;
  color: #909399;
}

.tip-text {
  font-size: 12px;
  color: #909399;
}

/* 保存按钮容器 */
.save-button-container {
  display: flex;
  align-items: center;
}

/* 编辑对话框样式 */
.edit-dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.edit-table-section .table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.edit-table-section .table-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.audit-info {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

/* 技术流程显示样式 */
.tech-flow-display {
  background-color: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  font-weight: 500;
  color: #1e40af;
  display: block;
  line-height: 1.4;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 工作日志提示信息样式 */
.worklog-tip {
  margin-top: 16px;
}

/* 快速选择区域样式 */
.quick-select-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  border: 1px solid #e9ecef;
}

.section-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16px;
  font-size: 16px;
}

.quick-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e9ecef;
}
</style>
